package com.hl.qzzpbackend.manager.upload;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.hl.qzzpbackend.config.CosClientConfig;
import com.hl.qzzpbackend.exception.BusinessException;
import com.hl.qzzpbackend.exception.ErrorCode;
import com.hl.qzzpbackend.exception.ThrowUtils;
import com.hl.qzzpbackend.manager.CosManager;
import com.hl.qzzpbackend.model.dto.file.ResumeUploadResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 简历上传
 * @author helong
 */
@Service
@Slf4j
public class FileResumeUpload {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    // 允许上传的文件后缀列表
    final List<String> ALLOW_SUFFIX_LIST = Collections.singletonList("pdf");

    final long ONE_MB = 1024 * 1024;

    // 处理文件来源
    protected void processFile(Object inputSource, File file) throws Exception {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }

    // 获取源文件名
    protected String getOriginalFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    // 校验文件
    public void validResume(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");

        // 1.校验文件大小
        long fileSize = multipartFile.getSize();
        ThrowUtils.throwIf(fileSize > ONE_MB * 10, ErrorCode.PARAMS_ERROR, "文件大小不能超过 10MB");

        // 2.校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!ALLOW_SUFFIX_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件格式不支持");
    }


    /**
     * 上传简历
     * @param inputSource 输入源
     * @param uploadPathPrefix 上传路径前缀
     * @return 简历基本信息
     */
    public ResumeUploadResult uploadResume(Object inputSource, String uploadPathPrefix) {
        // 1.校验文件
        validResume(inputSource);

        // 2.简历上传地址
        String uuid = RandomUtil.randomString(16);
        String originalFilename = getOriginalFilename(inputSource);
        // 自己拼接文件上传路径
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        File file = null;
        try {
            // 3.创建临时文件，获取文件到服务器
            file = File.createTempFile(uploadPath, null);
            // 处理文件来源
            processFile(inputSource, file);
            // 4.上传简历到对象存储
            cosManager.putObject(uploadPath, file);
            // 6.封装返回结果
            ResumeUploadResult uploadResumeResult = new ResumeUploadResult();
            uploadResumeResult.setUrl(String.format("%s%s", cosClientConfig.getHost(), uploadPath));
            uploadResumeResult.setName(originalFilename);
            uploadResumeResult.setPreviewUrl(String.format("%s%s%s",cosClientConfig.getHost(),uploadPath,"?ci-process=doc-preview&dstType=html"));
            return uploadResumeResult;
        } catch (Exception e) {
            log.error("简历上传到对象储存失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        }finally {
            // 6.临时文件清理
            deleteTempFile(file);
        }
    }



    /**
     * 删除临时文件
     * @param file 文件
     */
    public static void deleteTempFile(File file) {
        if(file == null){
            return;
        }
        // 删除临时文件
        boolean deleteResult = file.delete();
        if(!deleteResult){
            log.error("file delete error, filePath = {}",file.getAbsolutePath());
        }
    }
}
